var sqlite3 = require('sqlite3').verbose(),
    mkdirp = require('mkdirp'),
    fs = require('fs'),
    path = require('path'),
    readline = require('readline'),
    async = require('async'),
    helper = require('../libs/helper'),
    logger = require('../libs/logger').logger;

var sqliteDir = path.join(__dirname, '..', '..', 'sqlitedb');
logger.debug('创建sqlite目录', new Date().getTime());
mkdirp.sync(sqliteDir);

var db = new sqlite3.Database(path.join(sqliteDir, 'jwt.sqlite'));

function tx_handler(callback, commit) {
    return function () {
        var args = Array.prototype.slice.call(arguments);
        var err = args[0];
        if (err) db.run('rollback');
        else if (commit) db.run('commit');
        if (callback)
            callback.apply(this, args);
    }
}

var createTables = function (next) {
    db.serialize(function () {
        db.run("BEGIN");
        db.run("CREATE TABLE IF NOT EXISTS Users (UserID TEXT PRIMARY KEY, UserName TEXT, Password TEXT)", tx_handler());
        db.run("CREATE TABLE IF NOT EXISTS Notes (ID INTEGER PRIMARY KEY AUTOINCREMENT, Title TEXT, Narrative TEXT, CreateTime INTEGER, UpdateTime INTEGER)", tx_handler(function (err) {
            if (err) {
                logger.error(err);
                return process.exit(1);
            }
            if(next) next(err);
        }, true));
    });
};

createTables();


module.exports = {

    getDB: function(){
        return db;
    }

};